/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			mainwindow.cc
  \date			Aug 2011
  \author		TNick

  \brief		Contains the implementation for MainWindow class


 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @n
 Please read ReadMe.txt and Licence.txt in root folder @n
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @n

*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include    <main.h>


#include    <QSettings>
#include    <QStyleFactory>
#include    <QDir>
#include    <QMessageBox>
#include    <QCloseEvent>
#include    <QTimer>
#include    <QGraphicsPixmapItem>
#include    <QTimeLine>

#include    <data_store/pagedata.h>
#include    <data_store/pagemdl.h>
#include    <filters/abstractfilter.h>
#include    <filters/flt_regexnc.h>
#include    <filters/flt_words.h>


#include	<gui/mainwindow.h>
#include	"ui_mainwindow.h"




QString      s_default_page     (
	QObject::tr(
		"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n"
		"<HTML>\n"
		"<HEAD>\n"
		"    <TITLE> [Qt-creator] QSplitters</TITLE>\n"
		"</HEAD>"
		"<BODY BGCOLOR=\"#a0a0a0\">"
		"<H1>No selection</H1>"
		"<P>Select a page in the list to display content.</P>"
		"</BODY></HTML>"
		));

QString     def_url_to_search(
	"http://pastebin.com/archive"
	);

QString     def_base_path(
	"http://pastebin.com"
	);

QString     def_group_pattern(
	"<table"    /* starts with '<table' */
	"\\s+"      /* followed by one or more white space */
	"class=\"maintable\"" /* the class that we're interested in */
	"[^>]*"     /* till te end of the tag (not required) */
	"(.*)"      /* entire content in between */
	"</table>"  /* ends the group*/
	);
QString     def_url_pattern(
	"<a" /* starts with '<a' */
	"[^>]+" /* the end of <a> tag */
	"href=\"" /* href attribute */
	"([^\"]+)" /* this gets extracted */
	"\"[^>]*>" /* this is the end of the head tag */
	"(.*)"   /* also gets extracted */
	"<" /* a tag start ends our search */
	);

/*  INCLUDES    ============================================================ */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */

/* ------------------------------------------------------------------------- */
MainWindow::MainWindow	(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{


	/* create and further adjust the gui */
	ui->setupUi(this);
	ui->lv_pages->setRootIsDecorated(false);
	ui->webView->setHtml(s_default_page);


	/* web toolbar */
	initToolbars();


	/* create an model */
	pg_mdl = new PageMdl(this);
	ui->lv_pages->setModel(pg_mdl);
	sel_mdl = ui->lv_pages->selectionModel();


	/* connect pre-made components */
	initPreMade();


	/* User interface templates */
	initUITemplates();


	/* Skins (color schemes) */
	initSkins();


	/* the data related to actual retrieval */
	initWorkingSet();

	/* load filters and add them to chain */
	initFilters();

	/* main panel position and size */
	QSettings settings;
	settings.beginGroup("main_window_pos");

	QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
	QSize size = settings.value("size", QSize(800, 600)).toSize();
	move(pos);
	resize(size);

	settings.endGroup();

	scene.setSceneRect(0, 0, ui->gv_progress->width(), ui->gv_progress->height());
	scene.setBackgroundBrush(Qt::darkRed);
	ui->gv_progress->setScene(&scene);
	ui->gv_progress->setFrameStyle(0);
	ui->gv_progress->setAlignment(Qt::AlignLeft | Qt::AlignTop);
	ui->gv_progress->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	ui->gv_progress->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
//    ui->gv_progress->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
//    ui->gv_progress->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

	QTimeLine*  new_tl = new QTimeLine(500);
	new_tl->setFrameRange(0, 100);
	new_tl->setLoopCount(0);
	mov_icon = scene.addPixmap(
				QPixmap::fromImage(QImage(":/res/icons/ball.png")));
	setInterfEnabled(true);
	connect(new_tl, SIGNAL(frameChanged(int)),
			this, SLOT(slot_Advance(int )));
	new_tl->start();
	/* force the timer to start, if necessary */
	setPaused(paused());


	ui->statusbar->showMessage(tr("Ready"));

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
MainWindow::~MainWindow	(void)
{

	delete ui;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::initPreMade             (void)
{


	connect(ui->action_No_skin, SIGNAL(triggered()),
			this, SLOT(slot_No_skin()));
	connect(ui->action_LoadStySh, SIGNAL(triggered()),
			this, SLOT(slot_LoadStySh()));
	connect(ui->action_LayDir,  SIGNAL(triggered()),
			this, SLOT(slot_LayDir()));
	connect(ui->action_About,   SIGNAL(triggered()),
			this, SLOT(slot_About()));
	connect(ui->action_Help,    SIGNAL(triggered()),
			this, SLOT(slot_Help()));
	connect(ui->action_HelpCtx, SIGNAL(triggered()),
			this, SLOT(slot_HelpCtx()));
	connect(ui->action_AboutQt, SIGNAL(triggered()),
			qApp, SLOT(aboutQt()));

	connect(ui->action_LstCopyAll, SIGNAL(triggered()),
			this, SLOT(slot_LstCopy()));
	connect(ui->action_LstCopyName, SIGNAL(triggered()),
			this, SLOT(slot_LstCopyName()));
	connect(ui->action_LstCopyURL,  SIGNAL(triggered()),
			this, SLOT(slot_LstCopyAddr()));
	connect(ui->action_LstCopyDate,   SIGNAL(triggered()),
			this, SLOT(slot_LstCopyData()));
	connect(ui->action_LstDelete,    SIGNAL(triggered()),
			this, SLOT(slot_LstDel()));
	connect(ui->action_LstDeleteAll, SIGNAL(triggered()),
			this, SLOT(slot_LstDelAll()));
	connect(ui->action_LstDeleteFIn, SIGNAL(triggered()),
			this, SLOT(slot_LstDelFIn()));
	connect(ui->action_LstDeleteFOut, SIGNAL(triggered()),
			this, SLOT(slot_LstDelFOut()));
	connect(ui->action_ShowInBrowser, SIGNAL(triggered()),
			this, SLOT(slot_ShowInBrowser()));



	connect(ui->ck_FilterActive, SIGNAL(stateChanged (int)),
			this, SLOT(slot_FilteredChange(int)));
	connect(ui->ck_InvertFilter, SIGNAL(stateChanged (int)),
			this, SLOT(slot_FilterInOutChange(int)));

	connect(ui->webView, SIGNAL(loadFinished(bool)),
			this, SLOT(pageLoadEnd(bool)));
	connect(ui->webView, SIGNAL(loadStarted()),
			this, SLOT(pageLoadStart()));
	connect(ui->webView, SIGNAL(urlChanged(const QUrl &)),
			this, SLOT(pageURLChange(const QUrl &)));

	connect(ui->tx_Address, SIGNAL(editingFinished()),
			this, SLOT(slot_ReqLoadPage()));

	connect(ui->b_OptsFilt, SIGNAL(clicked()),
			this, SLOT(slot_FiltOpts()));
	connect(ui->b_OptsGen, SIGNAL(clicked()),
			this, SLOT(slot_GenOpts()));
	connect(ui->action_FiltOpts, SIGNAL(triggered()),
			this, SLOT(slot_FiltOpts()));
	connect(ui->action_GenOpts, SIGNAL(triggered()),
			this, SLOT(slot_GenOpts()));

	connect(ui->lv_pages, SIGNAL(customContextMenuRequested( const QPoint& )),
			this, SLOT(slot_LstCtxMnu( const QPoint& )));
	connect(ui->lv_pages, SIGNAL(doubleClicked( const QModelIndex& )),
			this, SLOT(	slot_LstDblClk ( const QModelIndex & )));



	connect(ui->b_Refresh, SIGNAL(clicked()),
			this, SLOT(slot_RefreshLst()));
	connect(ui->b_RunControl, SIGNAL(clicked()),
			this, SLOT(slot_StartStop()));

	/* selection change in list of pages */
	connect(
				sel_mdl,
				SIGNAL(currentChanged(
						   const QModelIndex & , const QModelIndex & )),
				this,
				SLOT(slot_PgLstSelChange(
						 const QModelIndex & , const QModelIndex & )));


	ui->action_About->setWhatsThis(ui->action_About->toolTip());
	ui->action_AboutQt->setWhatsThis(ui->action_AboutQt->toolTip());
	ui->action_Help->setWhatsThis(ui->action_Help->toolTip());
	ui->action_HelpCtx->setWhatsThis(ui->action_HelpCtx->toolTip());
	ui->action_LayDir->setWhatsThis(ui->action_LayDir->toolTip());
	ui->action_No_skin->setWhatsThis(ui->action_No_skin->toolTip());
	ui->action_LoadStySh->setWhatsThis(ui->action_LoadStySh->toolTip());
	ui->action_Exit->setWhatsThis(ui->action_Exit->toolTip());
	ui->action_GenOpts->setWhatsThis(ui->action_GenOpts->toolTip());
	ui->action_FiltOpts->setWhatsThis(ui->action_FiltOpts->toolTip());
	ui->action_LstCopyAll->setWhatsThis(ui->action_LstCopyAll->toolTip());
	ui->action_LstCopyName->setWhatsThis(ui->action_LstCopyName->toolTip());
	ui->action_LstCopyURL->setWhatsThis(ui->action_LstCopyURL->toolTip());
	ui->action_LstCopyDate->setWhatsThis(ui->action_LstCopyDate->toolTip());
	ui->action_LstDelete->setWhatsThis(ui->action_LstDelete->toolTip());
	ui->action_LstDeleteAll->setWhatsThis(ui->action_LstDeleteAll->toolTip());
	ui->action_LstDeleteFIn->setWhatsThis(ui->action_LstDeleteFIn->toolTip());
	ui->action_LstDeleteFOut->setWhatsThis(ui->action_LstDeleteFOut->toolTip());
	ui->action_ShowInBrowser->setWhatsThis(ui->action_ShowInBrowser->toolTip());

	ui->b_OptsGen->setWhatsThis(tr("General options affecting application's behaviour"));
	ui->b_OptsFilt->setWhatsThis(tr("Adjust filters options, enable or disable them"));
	ui->lv_pages->setWhatsThis(tr("List of retrieved pages"));
	ui->label->setWhatsThis(tr("List of retrieved pages"));
	ui->ck_FilterActive->setWhatsThis(tr("Display either all pages or only filtered ones"));
	ui->ck_InvertFilter->setWhatsThis(tr("Display either pages that do or that don't match the filter"));
	ui->b_RunControl->setWhatsThis(tr("Start/Stop autoscan for pages"));
	ui->b_Refresh->setWhatsThis(tr("Force a refresh in list of pages"));
	ui->gv_progress->setWhatsThis(tr("sellins - spirit of old miners in your computer"));
	ui->tx_Address->setWhatsThis(tr("Current web location"));
	ui->webView->setWhatsThis(tr("Preview"));
	ui->statusbar->setWhatsThis(tr("sellins - spirit of old miners in your computer"));
	ui->tb_web->setWhatsThis(tr("Controls for web preview"));











}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::initUITemplates         (void)
{

	connect(ui->menuUITpl, SIGNAL(triggered(QAction*)),
			this,SLOT(slot_UItplChange(QAction*)));
	QStringList	sty_list = QStyleFactory::keys();
	for (int i = 0; i < sty_list.count(); i++)
		{
			QAction* act_in =  ui->menuUITpl->addAction(sty_list.at(i));
			act_in->setStatusTip(tr("Predefined skin"));
			act_in->setCheckable(true);
			if (qApp->style()->objectName().compare(
						sty_list.at(i),Qt::CaseInsensitive))
				{ /* a value diffrent from 0 means this is not it */
					act_in->setChecked(false);
				}
			else
				{
					act_in->setChecked(true);
				}
		}

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::initSkins               (void)
{

	connect(
				ui->menuStySheet,
				SIGNAL(triggered(QAction*)),
				this,
				SLOT(slot_SkinChange(QAction*)));

	QDir	dir_ss(QCoreApplication::applicationFilePath());
	dir_ss.cd(QString("../StyleSheets"));
	if (dir_ss.exists())
		{
			QStringList filters;
			filters << "*.css";
			dir_ss.setNameFilters(filters);
			dir_ss.setFilter(QDir::NoDotAndDotDot | QDir::Files | QDir::Readable);
			filters = dir_ss.entryList();
			if (filters.count() > 0)
				{
					for (int i = 0; i < filters.count(); i++)
						{
							QAction* act_in =
									ui->menuUITpl->addAction(filters.at(i));
							act_in->setStatusTip(
										tr("StyleSheet located in "
										   "application's predefined folder"));

						}
				}
		}

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::initToolbars           (void)
{

	ui->tb_web->addAction(ui->webView->pageAction(QWebPage::Back));
	ui->tb_web->addAction(ui->webView->pageAction(QWebPage::Forward));
	ui->tb_web->addAction(ui->webView->pageAction(QWebPage::Reload));
	ui->tb_web->addAction(ui->webView->pageAction(QWebPage::Stop));
	ui->tb_web->addSeparator();
	ui->tb_web->addAction(ui->webView->pageAction(QWebPage::Cut));
	ui->tb_web->addAction(ui->webView->pageAction(QWebPage::Copy));
	ui->tb_web->addAction(ui->webView->pageAction(QWebPage::Paste));
	ui->tb_web->addSeparator();
	ui->tb_web->addAction(ui->webView->pageAction(QWebPage::SelectAll));


}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void        MainWindow::initWorkingSet         (void)
{
	/* get previously saved settings (or defaults) */
	QSettings settings;
	settings.beginGroup("WorkingData");

	msecs_to_sleep =
			settings.value(QString("msecs_to_sleep"),
						   DEFAULT_SEARCH_INTERVAL).toInt();
	s_job_name =
			settings.value(QString("s_job_name"),
						   QString("(no name)")).toString();
	s_url_to_search =
			settings.value(QString("s_url_to_search"),
						   def_url_to_search).toString();
	s_url_base =
			settings.value(QString("s_url_base"),
						   def_base_path).toString();
	s_group_pattern =
			settings.value(QString("s_group_pattern"),
						   def_group_pattern).toString();
	s_url_pattern =
			settings.value(QString("s_url_pattern"),
						   def_url_pattern).toString();
	cached_count =
			settings.value(QString("cached_count"),
						   false).toInt();
	flags = (FLG)
			settings.value(QString("flags"),
						   false).toInt();
	settings.endGroup();

	connect(app_timer, SIGNAL(timeout()), this, SLOT(timerEvent()));
	app_timer->setInterval(msecs_to_sleep);
	connect(l_manager, SIGNAL(finished(QNetworkReply*)),
			this, SLOT(replyFinished(QNetworkReply*)));

	// use same manager in webview, too
	ui->webView->page()->setNetworkAccessManager(l_manager);
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::initFilters         (void)
{
	Flt_RegExNC::initFilter();
	Flt_Words::initFilter();
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::saveSettings        (void)
{
	TRACE_EXECUTION("saving the settings","","");

	QSettings settings;

	settings.beginGroup("main_window_pos");
	settings.setValue("pos", pos());
	settings.setValue("size", size());

	settings.endGroup();



	settings.beginGroup("WorkingData");

	readMe();
	settings.setValue(QString("s_job_name"),s_job_name);
	settings.setValue(QString("s_url_to_search"),s_url_to_search);
	settings.setValue(QString("s_url_base"),s_url_base);
	settings.setValue(QString("msecs_to_sleep"),msecs_to_sleep);
	settings.setValue(QString("s_group_pattern"),s_group_pattern);
	settings.setValue(QString("s_url_pattern"),s_url_pattern);
	settings.setValue(QString("cached_count"),cached_count);
	settings.setValue(QString("flags"),flags);
	unlockMe();

	settings.endGroup();

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::setPaused               (bool b_set)
{
	if (b_set)
		{
			flags = (FLG)(flags | PAUSED);
			app_timer->stop();
			ui->b_RunControl->setText(tr("Start"));
			ui->statusbar->showMessage(tr("Autorefresh off"));
		}
	else
		{
			flags = (FLG)(flags & (~PAUSED));
			timerEvent();
			app_timer->start();
			ui->b_RunControl->setText(tr("Stop"));
			ui->statusbar->showMessage(tr("Autorefresh on"));
		}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::timerEvent (void)
{
	TRACE_EXECUTION("app_timer fired","","");

	QUrl    trg_url;
	int     mlsec_loc;

	if (!l_manager->networkAccessible())
		{
			QMessageBox::critical(
						g_MW,
						QObject::tr("Network error!!!"),
						QObject::tr("The networking is not available")
						);
			setPaused(true);
			return;
		}

	/* only allow one instance of this function */
	readMe();
	if (!interfEnabled())
		{
			TRACE_EXECUTION("  not ready to work"," (disabled) ","");
			unlockMe();
			return;
		}
	setInterfEnabled(false);

	trg_url.setUrl(s_url_to_search);
	mlsec_loc = msecs_to_sleep;
	unlockMe();


	/* get the web page */
	QNetworkRequest ntw_rq(trg_url);
	ntw_rq.setAttribute(QNetworkRequest::Attribute(QNetworkRequest::User + 1),
						QVariant(REQ_MAIN));
	ntw_rq.setRawHeader("User-Agent", "WebChecker");
	//ntw_rq.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
	//                    QNetworkRequest::PreferCache);
	ntw_rq.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
						QNetworkRequest::AlwaysNetwork);
	QNetworkReply * reply = l_manager->get(ntw_rq);
	connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
			this, SLOT(replyError(QNetworkReply::NetworkError)));
	connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
			this, SLOT(replySSLError(QList<QSslError>)));

	/* update the app_timer if there was a change */
	if (app_timer->interval() != mlsec_loc)
		app_timer->setInterval(mlsec_loc);

	/* allow future ticks */
	setInterfEnabled(true);

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::_loadStySh              (QString fileName)
{
	QString styleSheet;
	QFile   css_file;

	/* read file content */
	css_file.setFileName(fileName);
	if (!css_file.open(QFile::ReadOnly))
		{
			QMessageBox::warning(this, tr("Error"),
								 tr("Cannot read file %1:\n%2.")
								 .arg(fileName)
								 .arg(css_file.errorString()));
			return;
		}
	styleSheet = QLatin1String(css_file.readAll());
	css_file.close();

	/* and load it's content */
	qApp->setStyleSheet(styleSheet);
}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void            MainWindow::replyError             (
	QNetworkReply::NetworkError err_code)
{
	TRACE_EXECUTION("error recieved","","");

	QNetworkReply *reply = static_cast<QNetworkReply*>(sender());
	if (QNetworkReply::OperationCanceledError != err_code)
		{
			QMessageBox::critical(
						g_MW,
						QObject::tr("Network error!!!"),
						QObject::tr("Error code %1 recieved while "
									"attempting to retrieve\n"
									"%2\n\n"
									"%3.")
						.arg(err_code)
						.arg(reply->url().toString())
						.arg(reply->errorString())
						);
		}
}
/* ========================================================================= */

#ifndef QT_NO_OPENSSL
/* ------------------------------------------------------------------------- */
/// informed about an SSL error in the request
void            MainWindow::replySSLError           (
	const QList<QSslError> & errors)
{
	TRACE_EXECUTION("SSL error recieved","","");

	QNetworkReply *reply = static_cast<QNetworkReply*>(sender());

	QString errorString(tr("One or more SSL errors has occurred: \n"));
	foreach (const QSslError &error, errors) {
		errorString += error.errorString() + "\n";
	}

	if (QMessageBox::critical(
				g_MW,
				QObject::tr("Network error!!!"),
				errorString,
				QMessageBox::Abort | QMessageBox::Ignore
				) == QMessageBox::Abort)
		{

		}
	else
		{
			reply->ignoreSslErrors();
		}
}
/* ========================================================================= */
#endif


/* ------------------------------------------------------------------------- */
void            MainWindow::replyFinished (QNetworkReply* pReply)
{
	TRACE_EXECUTION("have a reply","","");

	ReqCommand i_req =(ReqCommand)
			pReply->request().attribute(
				QNetworkRequest::Attribute(QNetworkRequest::User + 1),
				QVariant(0)).toInt();


	switch (i_req)  {

	case    REQ_WEBPAGE :{// -------------------------
		TRACE_EXECUTION("  type is REQ_WEBPAGE","","");

		break;}
	default : /* REQ_MAIN  */{// -------------------------
		TRACE_EXECUTION("  type is REQ_MAIN","","");

		QByteArray data=pReply->readAll();
		QString s_scan(data);
		process_links(s_scan);

		if (!pReply->isFinished())
			pReply->abort();
		pReply->deleteLater();
		break;}

	}


}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::process_links       (QString s_scan)
{
	TRACE_EXECUTION("new data to process","","");

	PageMdl *   mdl = g_MW->pageModel();
	readMe();
	QString     loc_group_pattern = s_group_pattern;
	QString     loc_url_pattern = s_url_pattern;
	unlockMe();

	/* patter used to identify the table block */
	QRegExp regex(
				loc_group_pattern,
				Qt::CaseInsensitive, QRegExp::RegExp2 );
	regex.setMinimal(true);

	/* loop find links inside */
	int res = regex.indexIn(s_scan);
	int i_added = 0;
	if (res != -1)
		{
			// we have the table in the string
			QString table_text = regex.cap(0);
			bool flop = false;

			regex.setPattern(loc_url_pattern);
			int pos = 0;

			while ((pos = regex.indexIn(table_text, pos)) != -1) {
				if (flop == false)
					{
						flop = true;

						/* we have a link and a name */

						QString     the_url( regex.cap(1) );
						QString     the_name( regex.cap(2) );
						QUrl        new_u(the_url);
						if (new_u.isRelative())
							new_u = QUrl(s_url_base).resolved(new_u);
						the_url = new_u.toString();
						if (mdl->hasURL(the_url) == false)
							{
								/* create a new page */
								PageData * new_page =
										new PageData(the_url, the_name);

								mdl->appendNewPage(new_page);
								i_added++;
							}
					}
				else
					flop = false;
				pos += regex.matchedLength();
			}
		}

	if (i_added != 0)
		{
			slot_NewPagesRecived(i_added);
		}

}
/* ========================================================================= */



/* ------------------------------------------------------------------------- */
void        MainWindow::pageLoadStart           (void)
{
	ui->statusbar->showMessage(tr("Loading..."));
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::pageLoadEnd             (bool b_ok)
{
	if (b_ok)
		ui->statusbar->showMessage(tr("Loaded"));
	else
		ui->statusbar->showMessage(tr("Error loading page"));
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void       MainWindow::pageURLChange           (const QUrl & new_url)
{
	ui->tx_Address->setText(new_url.toString());
}
/* ========================================================================= */



/* ------------------------------------------------------------------------- */
void        MainWindow::closeEvent              (QCloseEvent *event)
{

	saveSettings();

	AbstractFilter::killFilters();

	event->accept ();

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::changeEvent             (QEvent *e)
{
	QMainWindow::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange:
		ui->retranslateUi(this);
		break;
	default:
		break;
	}
}
/* ========================================================================= */





/* ------------------------------------------------------------------------- */
void            MainWindow::slot_NewPagesRecived    (int new_count)
{

	qDebug() << "New data recieved";

	PageMdl * mdl = static_cast<PageMdl *>(ui->lv_pages->model());
	mdl->beginInsertRows(QModelIndex(),0,new_count-1);
	mdl->endInsertRows();
	ui->lv_pages->resizeColumnToContents(0);
	ui->lv_pages->resizeColumnToContents(1);
	ui->lv_pages->resizeColumnToContents(2);

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void            MainWindow::slot_ReqLoadPage        (void)
{
	ui->webView->setUrl(ui->tx_Address->text());
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
PageData *      MainWindow::currentPageD            (void)
{
	QModelIndexList sel_lst = sel_mdl->selectedIndexes();
	if (sel_lst.count() == 1)
		{
			QModelIndex  midx = sel_lst.at(0);
			PageData * p_data = static_cast<PageData *>(midx.internalPointer());
			if (p_data != NULL)
				{
					return p_data;
				}
		}
	return NULL;
}
/* ========================================================================= */



/*  CLASS    =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */


